use crate::image::ImageSegmentator;
use crate::prequire::{
  adb::{screenshot::ScreenshotCmd, shell::ShellCmd},
  BinaryCommand,
};
use crate::project::conf::project_conf::ProjectConf;
use crate::project::parser::{ParseOptions, Parser};
use anyhow::{anyhow, Result};
use indicatif::ProgressBar;
use std::fs::rename;
use std::path::Path;
use std::thread;
use std::time::Duration;
use walkdir::WalkDir;

pub struct KeywordSearchResultParser<'a> {
  conf: &'a ProjectConf,
}

impl<'a> KeywordSearchResultParser<'a> {
  pub fn new(conf: &'a ProjectConf) -> Self {
    KeywordSearchResultParser { conf }
  }
}

impl<'a> Parser for KeywordSearchResultParser<'a> {
  fn parse<P1: AsRef<Path>, P2: AsRef<Path>>(
    &self,
    input_dir: P1,
    out_dir: P2,
    opts: &ParseOptions,
  ) -> Result<Vec<String>> {
    self.ensure_out_dir(out_dir.as_ref());
    let out_raw_dir = self.ensure_out_raw_dir(out_dir.as_ref());
    let (m, sty) = self.create_indicator();
    let num = WalkDir::new(input_dir.as_ref())
      .max_depth(1)
      .into_iter()
      .filter_map(|entry| entry.ok())
      .filter(|d| {
        if let Some(e) = d.path().extension() {
          opts.exts.contains(&e.to_str().unwrap())
        } else {
          false
        }
      })
      .count();
    // pb负责从设备截图到本地
    let pb = m.add(ProgressBar::new(num as u64));
    pb.set_style(sty);

    m.println("开始处理!").unwrap();
    for (i, entry) in WalkDir::new(input_dir.as_ref())
      .max_depth(1)
      .into_iter()
      .filter_map(|entry| entry.ok())
      .filter(|d| {
        if let Some(e) = d.path().extension() {
          opts.exts.contains(&e.to_str().unwrap())
        } else {
          false
        }
      })
      .enumerate()
    {
      pb.set_message(format!("读取 item #{}", i + 1));
      println!("file=>{}", entry.path().display());
      thread::sleep(Duration::from_millis(500));
      pb.inc(1);
    }
    m.clear().unwrap();
    Ok(vec![])
  }
}
